package net.zoneland.knowledge.service.impl.search;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import net.zoneland.knowledge.config.SearchStrategyConfig;
import net.zoneland.knowledge.constant.Constants;
import net.zoneland.knowledge.enums.DictParentEnum;
import net.zoneland.knowledge.enums.TypeEnum;
import net.zoneland.knowledge.model.DictItem;
import net.zoneland.knowledge.model.QaResponse;
import net.zoneland.knowledge.service.DictItemService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 指向特殊配置的页面的关键字.
 *
 * @author: bcc
 * 2021/5/26
 */
@Service("searchOperationImplQueryNavigatePageWords")
public class SearchOperationImplQueryNavigatePageWords extends AbstractSearchOperation {

    /**
     * logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SearchOperationImplQueryNavigatePageWords.class);

    /**
     * guava缓存，获取内存
     */
    private static final Cache<String, Map<String, String>> cache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.HOURS).build();

    /**
     * 关键字.
     */
    private static final String KEY_WORD_KEY = "keyWordKey";

    @Autowired
    private DictItemService dictItemService;

    @Autowired
    private SearchStrategyConfig searchStrategyConfig;


    @Override
    public boolean needRun(final SearchDto searchDto) {
        if (searchStrategyConfig.isNavigatePageWords()) {
            return false;
        }
        return !searchDto.isStopSearch() && StringUtils.isNotEmpty(searchDto.getQaQueryDto().getQueryText());
    }

    /**
     * 获取固定词.
     *
     * @return 关键字列表
     */
    private Map<String, String> getKeyWordsList() throws ExecutionException {
        Map<String, String> map = cache.get(KEY_WORD_KEY, () -> {
            List<DictItem> dicts = dictItemService.findDictByParentId(DictParentEnum.SEARCH_NAVIGATE_PAGE_KEYWORD.getValue());
            if (CollectionUtils.isNotEmpty(dicts)) {
                Map<String,String> mapRs = new HashMap<>();
                for(DictItem dictItem:dicts) {
                    String desc = dictItem.getDescription();
                    if(null == desc) {
                        desc = " ";
                    }
                    mapRs.put(dictItem.getDictName(),desc);
                }
//                return dicts.stream().collect(Collectors.toMap(DictItem::getDictName,DictItem::getDescription));
                return mapRs;
            }
            //  guava 设置expireAfterWrite后返回null会报错
            return new HashMap<>(0);
        });
        return map;
    }

    @Override
    protected void doSearchOrDeal(final SearchDto searchDto) throws Exception {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("start SEARCH_NAVIGATE_PAGE_KEYWORD {}", searchDto);
        }
        Map<String, String> map =  getKeyWordsList();
        final String queryText = searchDto.getQaQueryDto().getQueryText();
        final List<String> categoryList = searchDto.getQaQueryDto().getCategoryList();
        List<Map<String,String>> rs = new ArrayList<>();
        for(String category: categoryList) {
            String key = category + Constants.STRING_SPLIT_FLAG_MIDDLE_LINE + queryText;
            if (map.containsKey(key)) {{
                Map<String,String> responseData = new HashMap<>();
                responseData.put("name", key);
                responseData.put("value", map.get(key));
                rs.add(responseData);
            }}
        }
        if (rs.size() > 0) {
            try {
                QaResponse qaResponse = new QaResponse();
//                String jsonStr = map.get(queryText);
//                jsonStr = jsonStr.replaceAll("\r", "").
//                        replaceAll("\n", "").
//                        replaceAll("\t", "");
//                qaResponse.setType(TypeEnum.OBJECT.getValue());
//                qaResponse.setData(GsonUtils.GSON.fromJson(jsonStr, Map.class));
                qaResponse.setType(TypeEnum.CUSTOM_PAGE_LIST.getValue());
                qaResponse.setData(rs);
                searchDto.setQaResponse(qaResponse);
                searchDto.setStopSearch(true);
                searchDto.setStopDeal(true);
            } catch (Exception e) {
                LOGGER.error("SEARCH_NAVIGATE_PAGE_KEYWORD error", e);
            }
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("end SEARCH_NAVIGATE_PAGE_KEYWORD {}", searchDto);
        }
    }



}
